package service

import (
	"gameserver/gcommon"
	"gameserver/server"
	"gameserver/server/Gateway/internal"

	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/logger"
	"gitee.com/night-tc/gobige/msgdef"
	"gitee.com/night-tc/gobige/serverMgr"
	"gitee.com/night-tc/gobige/service"
)

var _ internal.IService = &GatewayService{}

/*
Gateway服务器
*/
type GatewayService struct {
	*service.Service
	//客户端连接管理器
	ClientMgr *ClientMgr

	//服务器信息
	Sinfo *gcommon.ServiceConfig
}

func NewService(sinfo *gcommon.ServiceConfig) (result *GatewayService) {
	result = new(GatewayService)
	result.Sinfo = sinfo
	result.Service = service.NewService(sinfo.GlobalConfig, result)
	result.ClientMgr = NewClientMgr(result.GetThreadGo(), sinfo.ListenMap[global.ListenType_Outer], result.MsgHandler.GetNewSubHandler())
	result.ListenMap[global.ListenType_Outer] = result.ClientMgr.ListenAddr
	return
}

func (this *GatewayService) Init() (err error) {
	this.ClientMgr.RegMsgProc(&Client_Proc{this})
	this.RegMsgProc(&Service_Proc{this})
	if err = this.Service.Init(); err != nil {
		return err
	}
	if err = this.ClientMgr.Start(); err != nil {
		return err
	}

	return nil
}

// 监听需要主动连接的服务器逻辑
func (this *GatewayService) WatchServer() {
	/*
	   如果需要对某子服务器的分配器，做一些修改，可以在这里设置
	   Watch函数对同一个类型的只能Watch一次
	   做服发现一般有二个目的：
	   1、主动连接对方服务器；
	   2、管理用户去对应服务器时候，使用什么负载均衡的逻辑；
	*/
	this.DisMgr.Watch(server.ServerType_Game, this.Sinfo.GroupID, serverMgr.NewServerMapByMinID())

	this.Service.WatchServer()
}

func (this *GatewayService) Destroy() {
	this.ClientMgr.Stop()
	this.Service.Destroy()
}

//------------------------------------------------------------------------------
/* IMsgOwner */

// 处理消息前
func (this *GatewayService) OnMsgBefore(name string, msg msgdef.IMsg) {
	if name == "HeartBeat" {
		return
	}
	logger.Debugf(logger.LogKey_Msg, "OnMsgBefore:%s;", name)
}

// // 处理消息后
// OnMsged(name string, msg msgdef.IMsg)
// 处理RPC消息前
func (this *GatewayService) OnRpcBefore(name string, msg msgdef.IMsg) {
	logger.Debugf(logger.LogKey_Msg, "OnRpcBefore:%s;", name)

}

// // 处理RPC消息后
// OnRpced(name string, msg msgdef.IMsg)
